package cn.jwt.serviceImpl;


import cn.jwt.domain.ResponseResult;
import cn.jwt.entity.SysUser;
import cn.jwt.service.LoginServcie;
import cn.jwt.utils.JwtUtil;
import cn.jwt.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

@Service
public class LoginServcieImpl implements LoginServcie {

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private RedisCache redisCache;

    @Override
    public ResponseResult login(SysUser sysUser) {
        //AuthenticationManager的authenticate方法来进行用户认证
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(sysUser.getUserName(),sysUser.getPassword());
        Authentication authenticate = authenticationManager.authenticate(authenticationToken);
        //如果认证没通过，给出对应的提示
        if(Objects.isNull(authenticate)){
            throw new UsernameNotFoundException("登陆失败！");
        }
        //如果认证通过了，使用userid生成一个jwt jwt存入ResponseResult进行返回
        LoginSysUser loginSysUser =(LoginSysUser) authenticate.getPrincipal();
        String userid = loginSysUser.getSysUser().getId().toString();
        String jwt = JwtUtil.createJWT(userid);
        Map map=new HashMap();
        map.put("token",jwt);
        //把完成的用户信息存入redis userid作为key
        redisCache.setCacheObject("login:"+userid,loginSysUser);
        return new ResponseResult(200,"登录成功！",map);
    }

    @Override
    public ResponseResult logout() {
        //获取SecurityContextHolder中的用户id
        UsernamePasswordAuthenticationToken authentication =(UsernamePasswordAuthenticationToken) SecurityContextHolder.getContext().getAuthentication();
        LoginSysUser loginSysUser =(LoginSysUser) authentication.getPrincipal();
        Long userid = loginSysUser.getSysUser().getId();
        redisCache.deleteObject("login:"+userid);
        //删除Redis中的值
        return new ResponseResult(200,"注销成功！",null);
    }
}
